package com.cn.wanxi.servlet;

import com.cn.wanxi.dto.NewsModelDto;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/backNews")
public class BackNewsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//         1.拿到页面的值,首先判断前台拿过来的值是否有效
        String pageNum = req.getParameter("pageNum");
        int num = 0;
        if (pageNum == null) {
            num = 1;
        } else if ("".equals(pageNum)) {
            num = 1;
        } else {
            num = Integer.parseInt(pageNum);
        }

        String pageSize = req.getParameter("pageSize");
//        2.封装页面传递过来的数据
        PageModel pageModel = new PageModel();
//        pageModel.setPageNum(num < 2 ? 1 : num);
//        pageModel.setPageSize(pageSize == null || "".equals(pageSize) ? 8 : Integer.parseInt(pageSize));
//        3.调用service服务层
        INewsService newsService = new NewsServiceImpl();

        NewsModelDto newsModel = newsService.getNewsModel(pageModel);
//        4.返回页面（返回数据）
        JSONArray jsonArray = JSONArray.fromObject(newsModel);
        System.out.println(jsonArray.toString());
        resp.getWriter().println(jsonArray);

    }
}
